"use strict"


const Nls = require('alibabacloud-nls')
const config = {
  accessKeyId: 'LTAI5tMZaTKp3tkiCoZWaqzN',
  accessKeySecret: 'mpn9Y3TGWorEI1ZbvusP8fkotmUUy9',
  url: 'wss://nls-gateway-cn-beijing.aliyuncs.com/ws/v1',
  appkey: 'B4CLnDz6EYmy6kGq',
  token: 'e9e025a0ac56452a9d5db59e58befe96'
};



const fs = require("fs")
const sleep = (waitTimeInMs) => new Promise(resolve => setTimeout(resolve, waitTimeInMs))

const URL = "wss://nls-gateway.cn-shanghai.aliyuncs.com/ws/v1"
const APPKEY = config.appkey  //获取Appkey请前往控制台：https://nls-portal.console.aliyun.com/applist
const TOKEN = config.token      //获取Token具体操作，请参见：https://help.aliyun.com/document_detail/450514.html

let audioStream = fs.createReadStream("di.wav", {
  encoding: "binary",
  highWaterMark: 1024
})
let b1 = []

audioStream.on("data", (chunk) => {
  let b = Buffer.from(chunk, "binary")
  b1.push(b)
 
  return
})

audioStream.on("close", async ()=>{
    let st = new Nls.SpeechTranscription({
      url: URL,
      appkey:APPKEY,
      token:TOKEN
    })

    st.on("started", (msg)=>{
      console.log("Client recv started:", msg)
    })

    st.on("changed", (msg)=>{
      console.log("Client recv changed:", msg)
    })

    st.on("completed", (msg)=>{
      console.log("Client recv completed:", msg)
    })

    st.on("closed", () => {
      console.log("Client recv closed")
    })

    st.on("failed", (msg)=>{
      console.log("Client recv failed:", msg)
    })

    st.on("begin", (msg)=>{
      console.log("Client recv begin:", msg)
    })
    
    st.on("end", (msg)=>{
      console.log("Client recv end:", msg)
    })

    try {
      await st.start(st.defaultStartParams(), true, 6000)
    } catch(error) {
      console.log("error on start:", error)
      
    }

    try {
      for (let b of b1) {
        if (!st.sendAudio(b)) {
          throw new Error("send audio failed")
        }
        await sleep(20)
      }
    } catch(error) {
      console.log("sendAudio failed:", error)
      
    }

    try {
      console.log("close...")
      await st.close()
    } catch(error) {
      console.log("error on close:", error)
    }
    await sleep(2000)

})